
package com.dps.omc.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.omc.utils.SqlWarnAnalyzer;
import com.dps.omc.service.IArtifactService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import com.dps.omc.model.Artifact;
import com.dps.common.utils.IdGenerator;
import com.dps.common.utils.JsonResult;
import com.dps.common.utils.PageParam;
import com.dps.common.utils.Constants;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class ArtifactAction extends AbstractAdminController<IArtifactService>{

    @Autowired
    private IArtifactService artifactService;
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private SqlWarnAnalyzer sqlWarnAnalyzer;

    @RequestMapping(value="/artifact/list")
    public String list(Artifact artifact,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(artifact); 	
    	BizData4Page<Artifact> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("artifact", artifact);
    	return "/module/artifact/list";
    }    
    
    @RequestMapping(value="/artifact/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

    	model.addAttribute("artifact", new Artifact());
        return "module/artifact/edit";
    }    
    
    @RequestMapping(value="/artifact/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){
    	
    	Artifact artifact = artifactService.fetch(id);
    	model.addAttribute("artifact", artifact);
        return "module/artifact/edit";
    }    
    
    @RequestMapping(value="/artifact/save")
    @ResponseBody
    public String save(HttpServletRequest request,Artifact artifact){
		boolean isAddNew = StringUtils.isBlank(artifact.getId())?true:false;

		if(isAddNew)
		{
			artifact.setId(IdGenerator.createNewId());
            artifactService.add(artifact);
		}
		else
		{
			artifactService.update(artifact);
		}
        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }    
    
    @RequestMapping(value="/artifact/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	artifactService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }       
	
    protected Map getQueryMap(Artifact artifact)
    {
    	Map<String, Object> conditions = new HashMap();
    	
		conditions.put("artType", artifact.getArtType());		
		conditions.put("name", artifact.getName());		
		conditions.put("path", artifact.getPath());		
		conditions.put("sizeLength", artifact.getSizeLength());		
		conditions.put("createrId", artifact.getCreaterId());		
		conditions.put("createrName", artifact.getCreaterName());		
		conditions.put("updaterId", artifact.getUpdaterId());		
		conditions.put("updaterName", artifact.getUpdaterName());		
		conditions.put("createDate", artifact.getCreateDate());		
		conditions.put("updateDate", artifact.getUpdateDate());		
    	return conditions;
    }

//    @RequestMapping(value="/artifact/upload", method=RequestMethod.POST)
//    public String addUser(@RequestParam MultipartFile[] file, HttpServletRequest request) throws IOException {
//        for(MultipartFile myfile : file){
//            System.out.println("文件长度: " + myfile.getSize());
//            System.out.println("文件类型: " + myfile.getContentType());
//            System.out.println("文件名称: " + myfile.getName());
//            System.out.println("文件原名: " + myfile.getOriginalFilename());
//            System.out.println("========================================");
//            //可以使用FileUtils来保存文件，这里不再列出代码
//            //FileUtils.copyInputStreamToFile()方法会自动关闭IO流
//            //FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
//        }
//        return "success";
//    }

    @RequestMapping(value="/artifact/upload")
    public @ResponseBody String handleFileUpload(@RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {

                String originalName = file.getOriginalFilename();
                String newName = IdGenerator.createNewId()+originalName;
                long size = file.getSize();
                gridFsTemplate.store(file.getInputStream(), newName/*, "image/png"/*, metaData*/);
                Artifact artifact = new Artifact();
                String artifactId = IdGenerator.createNewId();
                artifact.setId(artifactId);
                artifact.setName(originalName);
                artifact.setPath(newName);
                artifact.setSizeLength(size);
                String artType = originalName.split("\\.")[1];
                artifact.setArtType(artType);
                this.sqlWarn(artifact,file,artType);
                artifactService.add(artifact);
                String path = "/";
                JSONObject json = new JSONObject();
                json.put("statusCode", "200");
                json.put("originalName",originalName);
                json.put("newName",newName);
                json.put("artifactId",artifactId);
                json.put("size",size);
                json.put("warnFlag",artifact.getWarnFlag());
                return json.toString();
//                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                JSONObject json = new JSONObject();
                json.put("statusCode", "300");
                json.put("msg", e.toString());
                return json.toString();
            }
        } else {
            JSONObject json = new JSONObject();
            json.put("statusCode", "300");
            json.put("msg","文件为空！");
            return json.toString();
        }
    }

    @RequestMapping(value="/artifact/uploadbatch")
    @ResponseBody
    public String uploadBatch(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){

        JSONObject model = new JSONObject();
        JSONArray datas = new JSONArray();
        String artifactIds = "";
        for(int i =0;i<files.length;i++) {
            JSONObject data = new JSONObject();
            if (!files[i].isEmpty()) {
                String originalName = files[i].getOriginalFilename();
                String newName = IdGenerator.createNewId()+originalName;
                long size = files[i].getSize();
                try {
                    gridFsTemplate.store(files[i].getInputStream(), newName/*, "image/png"/*, metaData*/);
                    Artifact artifact = new Artifact();
                    String artifactId = IdGenerator.createNewId();
                    artifact.setId(artifactId);
                    artifact.setName(originalName);
                    artifact.setPath(newName);
                    artifact.setSizeLength(size);
                    artifact.setArtType(originalName.split("\\.")[1]);
                    artifactService.add(artifact);
                    data.put("id",artifact.getId());
                    data.put("name",artifact.getName());
                    data.put("size",artifact.getSizeLength());
                    artifactIds+=artifact.getId()+",";
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            datas.add(data);
        }
        model.put("datas",datas);
        artifactIds = artifactIds.substring(0,artifactIds.length()-1);
        model.put("artifactIds",artifactIds);
        model.put("statusCode", "200");
        return model.toString();
    }

    private void sqlWarn(Artifact artifact,MultipartFile file,String artType) throws Exception {

        if(artType.equals("sql")||artType.equals("SQL")) {
            artifact.setWarnFlag(sqlWarnAnalyzer.analyse(file));
        }
        else
        {
            artifact.setWarnFlag(false);
        }
    }

//
//    private String getContent(MultipartFile file) throws Exception {
//
//        InputStream is = file.getInputStream();
//        byte[] b = readStream(is);
//        System.out.println(new String(b));
//        String str = new String(b);
////        System.out.println(str);
//        return str;
//    }
//
//    public static byte[] readStream(InputStream inStream) throws Exception {
//        int count = 0;
//        while (count == 0) {
//            count = inStream.available();
//        }
//        byte[] b = new byte[count];
//        inStream.read(b);
//        return b;
//    }


    @Override
    protected IArtifactService getMainService() {
        return artifactService;
    }

    @Override
    protected String getMainObjName() {
        return "artifact";
    }

    @Override
    protected String getViewTitle() {
        return "artifact";
    }
}
